<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
Object user = request.getSession().getAttribute("user");
if(user==null){
	response.sendRedirect(basePath+"login");
}
%>


<!DOCTYPE html>
<html>
  
  <head>
    <meta charset="UTF-8">
    <title>${sysconf.proname}</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="stylesheet" href="css/xadmin.css">
    <script type="text/javascript" src="js/jquery1.min.js"></script>
    <script type="text/javascript" src="js/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="js/xadmin.js"></script>
	  <script type="text/javascript" src="js/datautil.js"></script>
	<style type="text/css">
		.layui-btn-primary{background-color: white !important;}
		.urdbts,.selectbts{float: right;}
		/* .urdbts .layui-btn{display: none} */
		#whrers div{margin-left: 5px}
		#EXP{display: none}
		.hint_msg{text-align: center;margin: 1rem;color: #999;}
		
		table.itable tbody td {
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #666666;
	background-color: #ffffff;
}

table.itable  td {
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
    -o-text-overflow:ellipsis;
    -moz-text-overflow: ellipsis;
    -webkit-text-overflow: ellipsis;
}
	</style>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
      <script src="js/html5.min.js"></script>
      <script src="js/respond.min.js"></script>      
    <![endif]-->
  </head>
  
  <body style="overflow-x: scroll;">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a>数据管理</a><a><cite>数据列表</cite></a>
      </span>
      <a class="layui-btn layui-btn-small sxBtn" href="javascript:location.replace(location.href);" title="刷新">
        <i class="layui-icon">&#xe669;</i></a>
    </div>
    <div class="x-body">
      <div class="layui-row">
      	<div class="layui-form">
      		 
      		<blockquote class="layui-elem-quote ">
      		
      			<label class="layui-form-label">选择项目</label>
	      		<div class="layui-input-inline">
					<select  id="findSqlName" class="sphone" lay-filter="pro1" >
						<option>选择查询项目</option>
						<c:forEach items="${grouplist}" var="list">
							<option value="${list.id}">${list.classname}</option>
						</c:forEach>
					</select>
					<select id="findsql" class="sphone" lay-filter="pro2" >
						<option>选择查询项目</option>
					</select>
				</div>
				<div class="layui-input-inline urdbts">
					<a id="IM" class="layui-btn layui-btn-primary" style="display: none">导入</a>
					<a id="IN" class="layui-btn layui-btn-primary" style="display: none">添加</a>
					<a id="UP" class="layui-btn layui-btn-primary" style="display: none">修改</a>
					<a id="DE" class="layui-btn layui-btn-primary" style="display: none">删除</a>
				</div>
			</blockquote>
			
      	</div>
      	<br>
      	
        <form class="layui-form layui-col-md12 x-so"  action="curd/expBusToTxt" method="post">
       	 <blockquote class="layui-elem-quote ">
	       	<div class="layui-row">
			   <div class="layui-col-md9">
			   	  <label class="layui-form-label">查询条件</label>
			   	  <div class="layui-input-inline" id="whrers">
				     <input type="hidden" name="sqlid" value="">
			   	  </div>
			   </div>
			   <div class="layui-col-md3">
			      <div class="selectbts">
			          <a class="layui-btn serBtn"  lay-submit lay-filter="whereform" id="wheresubmit"><i class="layui-icon">&#xe615;</i>搜索</a>
			          <span id="EXP" >
							<!-- <a class="layui-btn excel">导出Excel</a> -->
							<button type="submit" class="layui-btn csv" >导出TXT</button>
					  </span>
		          </div>
			   </div>
			 </div>
        	</blockquote>
        	
          
        </form>
      </div>
	
      <!-- <table class="layui-table" id="test"  lay-data=""  lay-filter="test" style="margin: 0; min-width: 1300px;">
      	 <thead>
		    
		  </thead>
      </table> -->
      <fieldset class="layui-elem-field">
		  <legend id="proname">选择查询项目</legend>
		  <div class="layui-field-box" style="min-height: 450px;">
		    <table class="layui-table itable"  lay-filter="test" style="margin: 0">
				<thead><tr></tr></thead>
				<tbody></tbody>
			  </table>
		  </div>
		</fieldset>
      
			
		
	  <div id="pages" style="text-align: center;"></div>
     
    </div>
		<script type="text/javascript">
			
		function toolbar(data){
			var html='<a class=\"on\" onClick=\"x_open_show(\'编辑详情\',\'editApp?orgid='+data.ORG_ID+'&id='+data.ID+'\',\'900px\',\'550px\')\"><i class=\"layui-icon\">&#xe642;</i> 编辑</a>&#12288'
			if(data.STATUS==1){
				return html+='<a class=\"on\" onclick=\"updateState(4,'+data.ID+')\"><i class=\"layui-icon\">&#xe640;</i> 注销</a>'
			}else if(data.STATUS==4){
				return '<a ><i class=\"layui-icon\">&#xe642;</i> 编辑</a>&#12288<a ><i class=\"layui-icon\">&#xe640;</i> 注销</a>'
			}else{
				return html+='<a ><i class=\"layui-icon\">&#xe640;</i> 注销</a>'
			}
		}
		
	  var data_curr, data_limit,data_field;
		
	  var types = [];
      layui.use([ 'laydate','layer','table','form','laypage','upload'], function(){
		   // $ = layui.$;
		    laypage = layui.laypage;
		    laydate = layui.laydate;
		    table = layui.table;
		    upload = layui.upload;
		    form = layui.form;
		    var nowTime = new Date().valueOf();
		    var max = null;
		    
		    form.on('select(pro1)', function(data){
		    	findName(data.value)
		    });
		    
		    form.on('select(pro2)', function(data){
		    	find(data.value);
		    });
		    
		    form.on('submit(whereform)',function(data){
		    	var field  = data.field;
		    	console.log("whereform 表单提交:"+JSON.stringify(field));
		    	if(field.sqlid==""){
		    		layer.alert("请选择查询的项目")
		    		return false;
		    	}
		    	layer.load();
		    	$.post("curd/findCount",field,function(data){ //查询总页数
		    		layer.closeAll('loading'); 
					laypage.render({
					    elem: 'pages' //注意，这里的 test1 是 ID，不用加 # 号
						,limit:20
					    ,count: data.cou //数据总数，从服务端得到
					    ,layout: ['limit', 'prev', 'page', 'next','count']
					    ,jump: function(obj, first){
					        //obj包含了当前分页的所有参数，比如：
					        console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
					        console.log(obj.limit); //得到每页显示的条数
					        data_curr = obj.curr;
					        data_limit = obj.limit;
					        data_field = field;
					       findList(obj.curr, obj.limit,field);//查询数据
					        
					    }
					});
					
				},"JSON");
		    	
		    	
		    	return false;
		    });
		    
			  
		 })
		 

		</script>
		
		<script> /*curd操作*/

/* var laydate = layui.laydate;
var laypage = layui.laypage;
var upload = layui.upload; */
	
	$(function(){

		$("#UP").click(function(){//修改数据功能
			var td = $(".itable thead td").html();
			var up = $(".itable thead #exce_up").html();
			//alert(up)
			var name = $(this).text();
			if(td!=undefined&&up==undefined){
			 $(".itable thead tr").prepend("<td id='exce_up'>操作</td>");
			 $(".itable tbody tr").prepend("<td><a onclick='up($(this).parents(\"tr\").attr(\"rid\"))'>"+name+"</a></td>");				
			}
		})
		
		$("#DE").click(function(){//删除数据功能
			var td = $(".itable thead td").html();
			var de = $(".itable thead #exce_de").html();
			//alert(up)
			var name = $(this).text();
			if(td!=undefined&&de==undefined){
			 $(".itable thead tr").prepend("<td id='exce_de'>操作</td>");
			 $(".itable tbody tr").prepend("<td><a onclick='de($(this).parents(\"tr\").attr(\"rid\"))'>"+name+"</a></td>");				
			}
		})
		
		$("#IN").click(function(){//添加数据功能
			inss();
		})
		
		var im_index=0;
		$("#IM").click(function(){//批量导入数据功能
			var sqlid = $("#findsql").val();
			var proname = $("#proname").text();
			var imstr = "<div style='text-align: center;margin-top: 15px;'><div class='layui-upload-drag' id='filecsv'><i class='layui-icon'></i><p>点击上传，或将文件拖拽到此处</p></div><div style='margin:10px'><a style='color: blue;' href='load/uploadTemplate?sqlid="+sqlid+"'>"+proname+"</a></div></div>";
			im_index = layer.open({
				  type: 1,
				  title: '导入数据',
				  shadeClose: true,
				  shade: 0.8,
				  area: ['300px', '250px'],
				  content: imstr //iframe的url
			}); 
			
			 upload.render({ //允许上传的文件后缀
			    elem: '#filecsv'
			    ,url: 'load/uploadCsv?sqlid='+sqlid
			    ,accept: 'file' //普通文件
			    ,exts: 'csv' //只允许上传压缩文件
			    ,done: function(res){
			      //console.log(res)
			      if(res.res==1){
			    	  layer.msg("数据导入成功",function(){
			    		  layer.close(im_index);
			    	  });
			      }else{
			    	  layer.msg(res.msg);
			      }
			    }
			 });
			 
		})
	})
	
	var upstr = "";
	var up_index;
	function up(id){
		if(id!=null&&id!=undefined&&id!="undefined"){
			//alert("正在更新："+id)
			up_index = layer.open({
				  type: 1,
				  title: '更新数据',
				  shadeClose: true,
				  shade: 0.8,
				  area: ['450px', '60%'],
				  content: upstr //iframe的url
			}); 
			
			
			$.each($('#form_up').serializeArray(), function(){//根据id和index定位到数据，回填至Up表单
				//data-index
				var $input  = $("#form_up").find("input[name="+this.name+"]");
				var data_index = $input.attr("data-index");
			    var dd = $("tr[rid="+id+"] td").eq(data_index).text();
			    $input.val(dd);
			});
			$("#form_up").find("input[name=rid]").val(id);
			form.render();
			
		}else{
			layer.msg("无效的ID")
		}
	}
	
	function de(id){
		if(id!=null&&id!=undefined){
			//alert("正在删除："+id)
			layer.confirm('是否删除这条数据？', {
			  btn: ['删除','取消'] //按钮
			}, function(){
				 var sqlid = $("#findsql").val();
				 $.post("curd/delete",{"sqlid":sqlid,"rid":id},function(data){
					 if(data.res==1){
						$("tr[rid="+id+"]").hide();
						layer.msg("删除成功！");
					 }else{
						 layer.msg(data.msg);
					 }
				 },"JSON")
			});
		}else{
			layer.msg("无效的ID")
		}
	}
	
	var insstr = "";
	var in_index;
	function inss(title){		
		in_index = layer.open({
			  type: 1,
			  title: '添加数据',
			  shadeClose: true,
			  shade: 0.8,
			  area: ['450px', '60%'],
			  content: insstr //iframe的url
		}); 
		form.render();
	}

	function hides(){//隐藏所有操作
		$("#EXP").hide();
		$("#UP").hide();
		$("#DE").hide();
		$("#IN").hide();
	}
	
	
	//-----------查询报表数据-----------------------------------------------

	
	
	function findList(page,size,field){
		/*  var data = {"page":page,"size":size}; 
		var table = $('#form_wheres').serializeArray(); */
		 layer.load();
		 $.post("curd/findList?page="+page+"&size="+size,field,function(data){
			 var head=""
			 var body="";
			 if(data.list!=null){
			     var list = data.list.list;
				 for(var k in toLowerCase(list[0])){
					 if(k=="rownum_"){
						 continue;
					 }
					 head+="<td>"+k+"</td>"
				 }
				 for(var i in list){
					 var h = toLowerCase(list[i]);
					 body+="<tr rid='"+h["aid"]+"'>"
					 a:for(var k in h){
						 if(k=="rownum_"){
							 continue a;
						 }
						 var v = h[k];
						 body+="<td>"+(v==null?"":v)+"</td>"
					 }
					 body+="</tr>"
				 }
				 
				 $(".itable thead tr").html(head);
				 $(".itable tbody").html(body);

			 }else{
				 layer.msg(data.msg)
			 }
			 layer.closeAll("loading");
			
		},"JSON"); 
	}

	//-----------查询报表数据-----------------------------------------------
	
	
	
	function submit_in(){//插入表单
		var sqlid = $("#findsql").val();
		var data = {"sqlid":sqlid}
		var table = $('#form_in').serializeArray();
		 $.each(table, function() {
		      data[this.name] = this.value;
		 });
		 $.post("curd/insert",data,function(data){
			 if(data.res==1){
				 layer.msg("添加成功！",function(){
					 layer.close(in_index);
				 });
			 }else{
				 layer.msg(data.msg);
			 }
		 },"JSON")
		 
		 
		console.log(JSON.stringify(data));
		return false;
	}
	
	
	function submit_up(){
		var sqlid = $("#findsql").val();
		var data = {"sqlid":sqlid}
		var table = $('#form_up').serializeArray();
		 $.each(table, function() {
		      data[this.name] = this.value;
		 });
		 $.post("curd/update",data,function(data){
			 if(data.res==1){
				 layer.msg("更新成功！");
				 layer.close(up_index);
				 findList(data_curr, data_limit,data_field);
			 }else{
				 layer.msg(data.msg);
			 }
		 },"JSON")
		 
		 
		console.log(JSON.stringify(data));
		return false;
	}
	
</script>
		
		
		
<script>

	
	//find("${sqlid}");
	/*根据分组查询SQL名称*/
	function findName(classid) {
		/* var classid = $("#findSqlName").val(); */
		if(classid>0){
			$.post("back/findName",{"classid":classid},function(data){
				var list = data.namelist
				var html = "<option value='0'>选择查询项目</option>";
				
				for(var i=0;i<list.length;i++ ){
					html+='<option value="'+toLowerCase(list[i]).id+'">'+toLowerCase(list[i]).name+'</option>'
				}
				//alert(explain)
				$("#findsql").html(html);
				form.render('select');
			},"JSON")
		}
	}


	function find(id){
		if(id>0){
			$.get("back/findSql",{"id":id},function(data){
				var sql = data.sql
				var wheres = sql.WHERES;
				var limits = sql.LIMITS;
				var inserts = sql.INSERTS;
				var updates = sql.UPDATES;
				var buttonconf = sql.BUTTONCONF;
				/* buttonconf = buttonconf==null?{}:buttonconf; */
				
				if(updates!=null){
					updates = updates.field
				}
				var comments = data.comments;
				var explain = '';
				var html = "<input type='hidden' name='sqlid' value='"+id+"'/>";
				cou = data.cou;
				for(var i in comments ){
					explain+=comments[i].COLUMN_NAME+' : '+comments[i].COMMENTS+'\n'
				} 
				
				hides();
				
				if(limits!=null){//加载权限
					var lss = limits.split("|")
					for(var i in lss){
						var limit_flag = lss[i];
						var limit_name = buttonconf[limit_flag];
						if(limit_name!=null&&limit_name!=""){
							$("#"+limit_flag).text(limit_name);
						}
						
						if(limit_name=="hide"){
							$("#"+limit_flag).hide();
						}else{
							$("#"+limit_flag).show();
						}
					}
	
				
					if(limits.indexOf("SE")>=0){//具备查询权限
						for(var w in wheres){
							//-----------非必要参数---------------------
							var pattern = wheres[w].pattern;
							pattern = pattern==null||pattern==undefined?"":" pattern='"+pattern.substring(1,pattern.length-1)+"' ";
							
							var required = wheres[w].required;
							required = required==null||required==undefined?"":" required ";
							
							var title = wheres[w].title;
							title = title==null||title==undefined?"":" title='"+title+"' ";
						//------------------------------------------
		
							/* if(wheres[w].type=='date'||wheres[w].type=='datestr'){
								
								html+="<input type='text' class='date'  name='"+wheres[w].name+"' placeholder='"+wheres[w].explain+"' "+pattern+required+title+"/>";
							}else  */
							if(wheres[w].type=="select"){
								html+="<div class='layui-input-inline'><select id='"+wheres[w].name+"' name='"+wheres[w].name+"' > <option value=''>"+wheres[w].explain+"</option>"
								var select = wheres[w].select;
								for(var s in select){
									for(var key in select[s]){
										var value = select[s][key];
										html+="<option value='"+value+"'>"+key+"</option>"
										//alert("key:"+key+",,value:"+value)
									}
								}
								html+="</select></div>"
							}else{
								html+="<div class='layui-input-inline'><input class='layui-input'  type='"+wheres[w].type+"' name='"+wheres[w].name+"' placeholder='"+wheres[w].explain+"' "+pattern+required+title+" /></div>";
							}
						}
						
					//	$("#sql").val(sql.SQLTEXT);
						$("#wheres_content").val(JSON.stringify(wheres,null,4));
						$("#wheres_content").attr("onchange","updateWheres("+id+")")

						
					}
					
					
					if(limits.indexOf("IN")>=0){ //加载添加的数据
						
						if(inserts!=null&&inserts!=undefined){
							insstr = "<form class='layui-form' id='form_in' onsubmit='return submit_in();'><div class='layui-form-item'></div>";
							insstr = toForm(insstr,inserts);
							insstr+="<div class='layui-form-item'><div class='layui-input-block'><input class='layui-btn' type='submit' value='提交'/><input class='layui-btn' type='reset' value='重置'/> </div></div></form>"
						}else{
							insstr = "<p class='hint_msg'>请联系管理员配置<p>";//如果没有配置则空页面
						}
						
					}else{
						insstr = "<p class='hint_msg'>请联系管理员配置<p>";
					}
					
					if(limits.indexOf("UP")>=0){ //加载添加的数据
						
						if(updates!=null&&updates!=undefined){						
							upstr = "<form class='layui-form' id='form_up' onsubmit='return submit_up();'><div class='layui-form-item'></div> <input type='hidden' name='rid'>";
							upstr = toForm(upstr,updates);
							upstr+="<div class='layui-form-item'><div class='layui-input-block'><input class='layui-btn' type='submit' value='提交'/><input class='layui-btn' type='reset' value='重置'/> </div></div></form>";
						}else{
							upstr = "<p  class='hint_msg'>请联系管理员配置<p>";//如果没有配置则空页面
						}
						//alert(insstr);
					}else{
						upstr = "<p  class='hint_msg'>请联系管理员配置<p>";
					}
					
					
					$("#whrers").html(html);
					$("#explain").html(explain);
					$("#proname").text(sql.NAME);
					
					
					//同时绑定多个
					lay('input[type=datetime],input[type=datetimestr]').each(function(){laydate.render({elem: this,trigger: 'click',type: 'datetime'});});
					lay('input[type=dates],input[type=datestr]').each(function(){laydate.render({elem: this,trigger: 'click'});});
					lay('input[type=endtime],input[type=endtimestr]').each(function(){laydate.render(
							{	
								elem: this
								,trigger: 'click'
								,type: 'datetime'
								,ready: function(date){
					        		this.dateTime.hours=23;
					        		this.dateTime.minutes=59;
					        		this.dateTime.seconds=59;
				        		}
							}
					);});
					
					
					

					form.render('select');
					$("#wheresubmit").click();
					//laydate.render({elem: 'input[type=datetime],input[type=datetimestr]',type: 'datetime'})
					//laydate.render({elem: 'input[type=dates],input[type=datestr]'});//加载事件控件
				}			
				
			},"JSON")
		}
	}
	
	
	function toForm(insstr,inserts){
		for(var i in inserts){
			//-----------非必要参数---------------------
			var pattern = inserts[i].pattern;
			pattern = pattern==null||pattern==undefined?"":" pattern='"+pattern.substring(1,pattern.length-1)+"' ";
			
			var required = inserts[i].required;
			required = required==null||required==undefined?"":" required ";
			
			var title = inserts[i].title;
			title = title==null||title==undefined?"":" title='"+title+"' ";
			
			var index = inserts[i].index;
			index = index==null||index==undefined?"":" data-index='"+index+"' ";
			
		//------------------------------------------
			
			var rest = pattern+required+title+index;
			
			insstr += "<div class='layui-form-item'><label class='layui-form-label'>"+inserts[i].explain+"</label><div class='layui-input-inline'>";
		/* 	if(inserts[i].type=='date'||inserts[i].type=='datestr'){
				
				//insstr+="<input type='text' class='date'  name='"+inserts[i].name+"' placeholder='"+inserts[i].explain+"' "+rest+"/>";
			}else  */
				
			if(inserts[i].type=="select"){
				insstr+="<select id='"+inserts[i].name+"' name='"+inserts[i].name+"' > <option value=''>"+inserts[i].explain+"</option>"
				var select = inserts[i].select;
				for(var s in select){
					for(var key in select[s]){
						var value = select[s][key];
						insstr+="<option value='"+value+"'>"+key+"</option>"
						//alert("key:"+key+",,value:"+value)
					}
				}
				insstr+="</select>"
			}else{
				var value = inserts[i].value;
				insstr+="<input class='layui-input' type='"+inserts[i].type+"' name='"+inserts[i].name+"' placeholder='"+inserts[i].explain+"' "+rest+" value='"+(value==null?"":value)+"' />";
			} 
			
			insstr += "</div></div>";
		}
		
		return insstr;
	}
	
	
	
	
	
	/*修改筛选条件*/
	function updateWheres(id){
		var text = $("#wheres_content").val();
		$.post("back/updateWheres",{"sqlid":id,"text":text},function(data){
		   if(data.res==1){
				find(id);
			}else{
				layer.msg(data.msg);
			} 
		},"JSON");
	}
	

	var size=20;

	$(function(){

		$("#is_texts").click(function(){
			var id = $("#is_texts:checked").attr("id")
			if(id=='is_texts'){
				$("#texts").show()
			}else{
				$("#texts").hide()
			}
		})

		//点击查看统计
		$('.excel').click(function(){ 
		   var t = $('form').serializeArray();
		    var p = '';
		    for(var i in t){
		    	p+=t[i].name+"="+t[i].value+"&";
		    }
		    p = p.substring(0, p.length-1)
		    location.href='curd/expBus?'+ encodeURI(p);
			
		});
		
		$('.csv').click(function(){
			   var t = $('form').serializeArray();
			    var p = '';
			    for(var i in t){
			    	p+=t[i].name+"="+t[i].value+"&";
			    }
			    p = p.substring(0, p.length-1)
			    layer.msg('下载中，请耐心等待，<br/>关闭窗口将导致下载失败..', {
				  icon: 16
				  ,shade: 0.01
				  ,time:5000
				});
			   // location.href='curd/expBusToTxt?'+encodeURI(p);
		});

		$('.pages li').click(function(){
			$(this).addClass('cur').siblings().removeClass('cur');
		});
		//弹框关闭按钮
		$('.btn-close').click(function(){
			$('.dialog').addClass('hide');
		});
		
	})
</script>

  </body>

</html>